package com.design.pattern;

import java.time.chrono.IsoChronology;

public class SingletonPattern {
    public static void main(String[] args){
        SingleObject.getInstance().showMessage();
        SingleObject4 en = SingleObject4.INSTANCE;
        SingleObject4 en2 = SingleObject4.INSTANCE;
        System.out.println(en.equals(en2));
    }
}
//饿汉  线程安全
class SingleObject{
    private static SingleObject instance = new SingleObject();
    private SingleObject(){}

    public synchronized static SingleObject getInstance(){
        return instance;
    }
    public void  showMessage(){
        System.out.println("singleton message.");
    }
}

//懒汉 线程安全
class SingleObject1{
    private static SingleObject1 instance;
    private SingleObject1(){}
    public static  synchronized  SingleObject1 getInstance(){
        if (instance == null) {
            instance = new SingleObject1();
        }
        return instance;
    }
}
//双检锁/双重校验锁

class SingleObject2{
    private volatile static SingleObject2 singleton;
    private SingleObject2 (){}
    public static SingleObject2 getSingleton() {
        if (singleton == null) {
            synchronized (SingleObject2.class) {
                if (singleton == null) {
                    singleton = new SingleObject2();
                }
            }
        }
        return singleton;
    }
}

//登记式/静态内部类
class SingleObject3{
    private static class SingletonHolder {
        private static final SingleObject3 INSTANCE = new SingleObject3();
    }
    private SingleObject3 (){}
    public static final SingleObject3 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

//枚举
enum SingleObject4 {
    INSTANCE;
    public void whateverMethod() {
        System.out.println("test");
    }
}